<template>
  <el-select
    v-model="selectValue"
    style="width: 100%"
    :placeholder="placeholder"
    :disabled="disabled"
    clearable
    filterable
    @change="handleChange"
  >
    <el-option
      v-for="(item, index) in options"
      :key="index"
      :label="item.storehouseName"
      :value="item.storehouseCode"
    ></el-option>
  </el-select>
</template>

<script setup name="UserSelect">
import { listStorehouse } from "@/api/storehouse/storehouse";
import { toRefs, ref, watch } from "vue";

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "",
  },
  line: {
    type: [String, Number],
    default: "",
  },
  section: {
    type: [String, Number],
    default: "",
  },
  autoSelect: {
    type: Boolean,
    default: false,
  },
  customOptions: {
    type: Array,
    default: null,
  },
});

const { disabled, line, section, autoSelect, customOptions } = toRefs(props);

const selectValue = defineModel();
const selectName = defineModel("name");
const options = ref([]);
const emit = defineEmits(["change"]);
watch(
  () => line.value,
  (val) => {
    if (!customOptions.value && val) {
      getList();
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => section.value,
  () => {
    if (!customOptions.value && (line.value || section.value)) {
      getList();
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => customOptions.value,
  (val) => {
    options.value = val;
  },
  {
    immediate: true,
  }
);

function handleChange(val) {
  let selected = null;
  for (let i = 0; i < options.value.length; i++) {
    if (val === options.value[i].storehouseCode) {
      selected = options.value[i];
      break;
    }
  }
  selectName.value = selected?.storehouseName;
  emit("change", selected);
}

function getList() {
  console.log(11);

  listStorehouse({
    lineCode: line.value,
    sectionCode: section.value,
    pageSize: 1000,
    pageNum: 1,
  }).then((res) => {
    options.value = res.rows;
    if (autoSelect.value && !selectValue.value) {
      selectValue.value = options.value.length ? options.value[0].storehouseCode : "";
      selectName.value = options.value.length ? options.value[0].storehouseName : "";
    }
  });
}
// getList();
</script>
